package com.xd.case1;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DistributeClient {

    private String connectString = "zookeeper1:2181,zookeeper2:2181,zookeeper3:2181";
    private int sessionTimeout = 100000000;
    private ZooKeeper zk = null;
    private String parentNode = "/servers";

    public static void main(String[] args) {
        DistributeClient client = new DistributeClient();

        try {
            //创建到zookeeper客户端的连接
            client.getConnection();

            //监视服务器（就是获取临时节点（server）的信息）
            client.getServerList();

            //业务功能
            client.business();
            
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }


    }

    private void business() throws InterruptedException {
        System.out.println("client is working...");
        Thread.sleep(Long.MAX_VALUE);
    }

    private void getServerList() throws InterruptedException, KeeperException {
        // 1 获取服务器子节点信息，并且对父节点进行监听。获取的是“servers”下的所有子节点
        List<String> children = zk.getChildren(parentNode, true);

        // 2 存储服务器信息列表
        ArrayList<String> servers = new ArrayList<>();

        // 3 遍历所有节点，获取节点中的主机名称信息
        for (String child : children) {
            //获取“servers”下的所有子节点的值
            byte[] data = zk.getData(parentNode + "/" + child, false, null);
            servers.add(new String(data));
        }

        // 4 打印服务器列表信息
        System.out.println(servers);
    }

    private void getConnection() throws IOException {
        zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                try {
                    // 再次启动监听，即回调函数中在此调该方法
                    getServerList();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (KeeperException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
